package com.doraro.coal.moudle.user.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.doraro.coal.exception.R;
import com.doraro.coal.utils.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static com.doraro.coal.utils.WebConstant.LOGIN_PAGE;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author doraro
 * @since 2019-09-26
 */
@Controller
@RequestMapping("/user/public")
public class UserRestController {
    @GetMapping("/code")
    public void code(HttpSession session,HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.write(response.getOutputStream());
        String checkcode=lineCaptcha.getCode();
        System.out.println("验证码:"+checkcode);
        session.setAttribute("checkcode",checkcode);

    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public R login(@RequestParam String username,@RequestParam  String password,
                   @RequestParam  String checkcode,
                   HttpSession hsession) {
        Subject subject = SecurityUtils.getSubject();
        String code=(String)hsession.getAttribute("checkcode");
        if(!StringUtils.equals(checkcode,code)){
           return R.fail("验证码错误");
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        subject.login(token);
        hsession.removeAttribute("checkcode");
        hsession.setAttribute("user",ShiroUtils.getUserEntity());
        return R.success();
    }

    @RequestMapping("/logout")
    public String logout(){
        ShiroUtils.logout();
        return LOGIN_PAGE;
    }





}

